import json
import logging
from datetime import datetime, timedelta
from django import forms

_LOGGER = logging.getLogger(__name__)


class JsonArrayDateField(forms.Field):
    def __init__(self, required=True, *args, **kwargs):
        super(JsonArrayDateField, self).__init__(*args, **kwargs)
        self.required = required

    def clean(self, value):
        try:
            if not self.required and not value:
                return []
            json_array_date = json.loads(value)
            assert isinstance(json_array_date, list)
            assert len(json_array_date) in [0, 2]
            cleaned_data = []
            for date_str in json_array_date:
                try:
                    datetime_obj = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
                except:
                    datetime_obj = datetime.strptime(date_str, '%Y-%m-%d')
                cleaned_data.append(datetime_obj)
        except:
            raise forms.ValidationError("Invalid data in JsonArrayDateField")
        return cleaned_data


class JsonArrayField(forms.Field):
    def __init__(self, required=True, specific_type=None, *args, **kwargs):
        super(JsonArrayField, self).__init__(*args, **kwargs)
        self.required = required
        self.specific_type = specific_type

    def clean(self, value):
        try:
            if not self.required and not value:
                return []
            json_array = json.loads(value)
            assert isinstance(json_array, list)
            if self.specific_type is not None:
                json_array = [self.specific_type(element) for element in json_array]
        except:
            raise forms.ValidationError("Invalid data in JsonArrayField")
        return json_array


class JsonField(forms.Field):
    def __init__(self, required=True, *args, **kwargs):
        super(JsonField, self).__init__(*args, **kwargs)
        self.required = required

    def clean(self, value):
        try:
            if not self.required and not value:
                return {}
            assert isinstance(value, dict)
        except:
            raise forms.ValidationError("Invalid data in JsonArrayField")
        return value


class DateTimeStringField(forms.Field):
    def __init__(self, required=True, to_utc=False, to_date=False, to_str=True, *args, **kwargs):
        super(DateTimeStringField, self).__init__(*args, **kwargs)
        self.required = required
        self.to_utc = to_utc
        self.to_date = to_date
        self.to_str = to_str

    def clean(self, value):
        try:
            if not self.required and not value:
                return None
            try:
                datetime_obj = datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
            except:
                datetime_obj = datetime.strptime(value, '%Y-%m-%d')
            if self.to_utc:
                datetime_obj = datetime_obj - timedelta(hours=8)
            if self.to_str:
                res = str(datetime_obj)
                if self.to_date:
                    res = res.split(' ')[0]
            else:
                res = datetime_obj
        except:
            raise forms.ValidationError("Invalid data in AgentAlipayJsonField")
        return res


class UserIDStringField(forms.Field):
    def __init__(self, required=True, *args, **kwargs):
        super(UserIDStringField, self).__init__(*args, **kwargs)
        self.required = required

    def clean(self, value):
        try:
            if not self.required and not value:
                return []
            res = []
            for _user_id in value.split(','):
                if _user_id:
                    res.append(int(_user_id.replace(' ', '')))
        except:
            raise forms.ValidationError("Invalid data in AgentAlipayJsonField")
        return res




